"""
数据库工具类
"""
import sqlite3
import logging
from typing import List, Dict, Any
from config.database_config import DATABASE, TABLES


class DatabaseManager:
    """数据库管理器"""

    def __init__(self, db_path: str = None):
        self.db_path = db_path or DATABASE['NAME']
        self.logger = logging.getLogger(__name__)

    def get_connection(self):
        """获取数据库连接"""
        return sqlite3.connect(self.db_path)

    def create_tables(self):
        """创建数据表"""
        with self.get_connection() as conn:
            cursor = conn.cursor()

            for table_name, fields in TABLES.items():
                columns = []
                primary_keys = fields.get('primary_key', [])

                for field_name, field_type in fields.items():
                    if field_name != 'primary_key':
                        columns.append(f"{field_name} {field_type}")

                if primary_keys:
                    pk_str = ', '.join(primary_keys)
                    columns.append(f"PRIMARY KEY ({pk_str})")

                sql = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(columns)})"
                cursor.execute(sql)

        self.logger.info("数据表创建完成")

    def insert_data(self, table: str, data: Dict[str, Any]):
        """插入数据"""
        with self.get_connection() as conn:
            cursor = conn.cursor()

            columns = ', '.join(data.keys())
            placeholders = ', '.join(['?' for _ in data])
            sql = f"INSERT OR REPLACE INTO {table} ({columns}) VALUES ({placeholders})"

            cursor.execute(sql, list(data.values()))

    def fetch_data(self, table: str, conditions: Dict[str, Any] = None) -> List[Dict]:
        """查询数据"""
        with self.get_connection() as conn:
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()

            sql = f"SELECT * FROM {table}"
            params = []

            if conditions:
                where_clauses = []
                for key, value in conditions.items():
                    where_clauses.append(f"{key} = ?")
                    params.append(value)
                sql += f" WHERE {' AND '.join(where_clauses)}"

            cursor.execute(sql, params)
            return [dict(row) for row in cursor.fetchall()]